import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import $http from '@/api/request.js'
// 按需引入消息提示组件，因为在vuex仓库中，访问不到this.$message
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: [],
    userCart: [],
    userCollection: []
  }
}

const state = getDefaultState()

const mutations = {
  // #region
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // #endregion
  // 获取用户基本信息
  async getUserInfo(state) {
    const res = await $http({ url: '/api/public/v1/admin/getuserinfo', method: 'get' })
    if (res.meta.status !== 200) return Message({ message: '获取用户信息失败', type: 'error' })
    state.userInfo = res.message
  },
  // 通过用户名获取用户购物车数据
  async getUserCart(state, username) {
    const res = await $http({ url: `/api/public/v1/admin/getusercart?username=${username}`, method: 'get' })
    if (res.meta.status !== 200) {
      this.commit('user/clearUserCart')
      Message.error(res.meta.msg)
      return
    }
    if (res.message.cart.length === 0) {
      this.commit('user/clearUserCart')
      Message.info('该用户购物车数据为空')
      return
    }
    Message.success('查询成功')
    state.userCart = res.message.cart
  },
  // 切换用户购物车中商品勾选状态
  // updateGoodsState(state, val) {
  //   let result = state.userCart.find(item => item.goods_id === val.goods_id)
  //   if (result) {
  //     result.goods_state = !result.goods_state
  //   }
  //   // 更新数据库中用户购物车数据
  //   this.commit('user/updateUserCart', val.username)
  // },
  // 更新数据库中用户购物车数据
  async updateUserCart(state, username) {
    const res = await $http({ url: '/api/public/v1/admin/updateusercart', data: { username, cart: state.userCart }, method: 'post' })
    if (res.meta.status !== 200) return Message.error('删除失败')
    Message.success(res.meta.msg)
  },
  // 删除用户购物车中的某个商品
  deleteCartGoods(state, val) {
    state.userCart = state.userCart.filter(item => item.goods_id !== val.goods_id)
    // 更新数据库中用户购物车数据
    this.commit('user/updateUserCart', val.username)
  },
  // 清空页面中（vuex仓库中）购物车数据
  clearUserCart(state) {
    state.userCart = []
  },
  // 通过用户名获取用户收藏商品数据
  async getUserCollection(state, username) {
    const res = await $http({ url: `/api/public/v1/admin/getusercollection?username=${username}`, method: 'get' })
    if (res.meta.status !== 200) {
      this.commit('user/clearUserCollection')
      Message.error(res.meta.msg)
      return
    }
    if (res.message.collection.length === 0) {
      this.commit('user/clearUserCollection')
      Message.info('该用户暂无收藏的商品')
      return
    }
    Message.success('查询成功')
    state.userCollection = res.message.collection
  },
  // 清空页面中（vuex仓库中）收藏商品数据
  clearUserCollection(state) {
    state.userCollection = []
  },
  // 删除用户收藏夹中的某个商品
  deleteCollectGoods(state, val) {
    state.userCollection = state.userCollection.filter(item => item.goods_id !== val.goods_id)
    // 更新数据库中用户收藏商品数据
    this.commit('user/updateUserCollection', val.username)
  },
  // 更新数据库中用户收藏商品数据
  async updateUserCollection(state, username) {
    const res = await $http({ url: '/api/public/v1/admin/updateusercollection', data: { username, collection: state.userCollection }, method: 'post' })
    if (res.meta.status !== 200) return Message.error('删除失败')
    Message.success(res.meta.msg)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          const { name, avatar } = data

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
